﻿using MonoDevelop.Psm.Vita;
using System;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CDude.Vita
{
    internal partial class RawDataForm : Form
    {
        private VCg_MainForm mainform;
        private VitaSerialPort port;

        public RawDataForm(VCg_MainForm mainform)
        {
            this.mainform = mainform;
            InitializeComponent();
        }

        private void RawDataForm_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Owner != null)
                this.Location = new Point(this.Owner.Left + this.Owner.Size.Width / 2 - this.Size.Width / 2, this.Owner.Top + this.Owner.Size.Height / 2 - this.Size.Height / 2);

            if (this.Visible)
                port = new VitaSerialPort(mainform.connection.Device.Name, new PsmVitaDevice(mainform.connection.Device));
        }

        private void RawDataForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ((VCg_MainForm)this.Owner).Enabled = true;
            this.Visible = false;
            e.Cancel = true;
        }

        private void copyRButton_Click(object sender, EventArgs e)
        {
            sendHexBox.Text = BitConverter.ToString(textStringToByteArray(sendASCIIBox.Text)).Replace('-', ' ');
        }

        private byte[] textStringToByteArray(string s)
        {
            try
            {
                return Encoding.ASCII.GetBytes(s);
            }
            catch
            {
                return null;
            }
        }

        private void sendASCIIRadio_CheckedChanged(object sender, EventArgs e)
        {
            sendASCIIBox.ReadOnly = !sendASCIIRadio.Checked;
            sendHexBox.ReadOnly = sendASCIIRadio.Checked;
        }

        private void copyLButton_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] bytes = hexStringToByteArray(sendHexBox.Text);
                sendASCIIBox.Text = Encoding.ASCII.GetString(bytes);
            }
            catch { }
        }

        private byte[] hexStringToByteArray(string s)
        {
            try
            {
                byte[] bytes = new byte[s.Count<char>(p => p == ' ') + 1];
                for (int i = 0; i < bytes.Length; i++)
                {
                    bytes[i] = Convert.ToByte(sendHexBox.Text.Replace(" ", "").Substring(i * 2, 2), 16);
                }
                return bytes;
            }
            catch
            {
                return null;
            }
        }

        private void sendHexRadio_CheckedChanged(object sender, EventArgs e)
        {
            if (!sendASCIIRadio.Checked && sendHexRadio.Checked)
                sendHexBox.ReadOnly = false;
        }

        private void sendHexBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.KeyChar = char.ToUpper(e.KeyChar);
            e.Handled = !(Char.IsDigit(e.KeyChar) || (e.KeyChar >= 'A' && e.KeyChar <= 'F') || e.KeyChar == ' ' || e.KeyChar == '\b');
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            byte[] buffertosend = null;

            if (sendASCIIRadio.Checked)
                buffertosend = textStringToByteArray(sendASCIIBox.Text);
            else if (sendHexRadio.Checked)
                buffertosend = hexStringToByteArray(sendHexBox.Text);

            if (mainform.breakOut()) return;
            toggleProgressForm();

            Task worktask = new Task(() =>
            {
                //VitaSerialPort port = new VitaSerialPort(GetVitaPortWithSerial(mainform.connection.Device.Name));
                //port.Open();
                port.Write(buffertosend, 0, buffertosend.Length);
                toggleProgressForm();
            });

            worktask.Start();

            //new Task(() => { mainform.verifyWorkingDevices(ref worktask); }).Start();
        }

        private void toggleProgressForm()
        {
            this.Enabled = !this.Enabled;
            mainform.progressform.Visible = !mainform.progressform.Visible;
        }

        private string GetVitaPortWithSerial(string serial)
        {
            ManagementClass class2 = new ManagementClass("Win32_SerialPort");
            string vitaDebugPnpDeviceID = @"USB\VID_054C&PID_069B\" + serial;
            while (true)
            {
                foreach (ManagementBaseObject obj2 in class2.GetInstances())
                {
                    if ((obj2.GetPropertyValue("PNPDeviceID") as string).IndexOf(vitaDebugPnpDeviceID, StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        string str2 = obj2.GetPropertyValue("Caption").ToString();
                        if ((str2 != null) && str2.Contains("PSM USB Debug"))
                        {
                            string str3 = obj2.GetPropertyValue("DeviceID").ToString();
                            if (!string.IsNullOrEmpty(str3))
                            {
                                return str3;
                            }
                        }
                    }
                }
                Thread.Sleep(100);
            }
        }

        private void readButton_Click(object sender, EventArgs e)
        {
            byte[] buffer = new byte[(int)readLength.Value];

            if (mainform.breakOut()) return;

            toggleProgressForm();

            Task worktask = new Task(() =>
            {
                VitaSerialPort port = new VitaSerialPort(GetVitaPortWithSerial(mainform.connection.Device.Name), new PsmVitaDevice(mainform.connection.Device));
                port.Open();

                //while (true)
                //{
                if (port.BytesToRead >= buffer.Length)
                    readBox.Text += port.Read(buffer, 0, buffer.Length);

                Thread.Sleep(30);

                //}

                //port.Close();
                toggleProgressForm();
            });

            worktask.Start();

            //new Task(() => { mainform.verifyWorkingDevices(ref worktask); }).Start();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            port.Open();
            port.Write(new byte[] { 01, 00, 00, 00, 0x0A, 00, 00, 00 }, 0, 8);
            port.Write(new byte[] { 09, 00, 00, 00, 05, 00, 00, 00, 0x30, 0x2E, 0x39, 0x39, 00 }, 0, 13);

            //port.Close();
            //toggleProgressForm();
        }
    }
}